<template>
  <div id="labCompanyFeeitemDiv">
    <Splitpanes>
      <Pane size="60">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input style="width: 180px" v-model="searchCompanyFeeForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findCompanyFeeitemList" @keyup="keyupCompanyFeeEnter" @search-click="findCompanyFeeitemList()"></vxe-input>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="ploading" @click="findCompanyFeeitemList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveCompanyFeeitemList"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchCompanyFee"></vxe-button>
            <!-- <div class="msgDiv">双击移除</div> -->
          </template>
        </vxe-toolbar>
        <div class="rightTable">
          <!--@cell-dblclick="tatItemRowClick"   双击移除-->
          <vxe-table ref="tatItemTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="companyFeeList" :loading="ploading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>
            <vxe-column type="seq" title="#" width="30"></vxe-column>
            <vxe-column field="feeCode" title="项目编号" width="80"></vxe-column>
            <vxe-column field="feeName" title="项目名称" min-width="100"></vxe-column>
            <vxe-column field="discount" title="折扣" width="80" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.discount" placeholder="" type="float" :min="0" :max="1" @blur="funDiscountPrice(row)"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column field="price" title="折扣价" width="80" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.price" placeholder="" type="number" @blur="funDiscountPrice1(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="origPrice" title="原价" min-width="100"></vxe-column>

            <vxe-column field="brokerageType" title="佣金方式" width="80" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ formatCommon(transKindList, row.brokerageType) }}</span>
              </template>
              <template #edit="{ row, rowIndex, column }">
                <!-- 选择字典  -->
                <vxe-select v-model="row.brokerageType">
                  <vxe-option v-for="hobj in transKindList" :key="hobj.code" :value="hobj.code" :label="hobj.name"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>

            <vxe-column field="brokerage" title="佣金值" width="80" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.brokerage" placeholder="" type="float" :min="0" :max="1" @blur="funDiscountPrice1(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="brokerageCosts" title="销售提成" min-width="100" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.brokerageCosts" placeholder="" type="number"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column field="seq" title="顺序" width="50" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.seq" placeholder="" type="text"></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane size="40">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input style="width: 180px" v-model="searchForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findFeeItemList" @keyup="keyupEnter" @search-click="findFeeItemList()"></vxe-input>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="floading" @click="findFeeItemList"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="rightTable">
          <vxe-table ref="feeItemTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="feeItemList" :loading="floading" @cell-dblclick="feeItemRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
            <vxe-column type="seq" title="#" width="30"></vxe-column>
            <vxe-column field="feeCode" title="项目编号" width="90"></vxe-column>
            <vxe-column field="feeName" title="项目名称" min-width="180"></vxe-column>
            <vxe-column field="price" title="单价" align="right" width="60"></vxe-column>
          </vxe-table>
        </div>

      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { IsEmpty } from '@/utils/common';
defineExpose({ initPage });
let inspectCompany: any = reactive({});
let floading = ref(false);
let ploading = ref(false);

let feeItemList = reactive([]);
let companyFeeList = reactive([]);
let transKindList: any = reactive([
  { code: '1', name: '按比例' },
  { code: '2', name: '固定值' }
]);
let searchForm = reactive({
  seachValue: ''
});
let searchCompanyFeeForm = {
  seachValue: ''
};
function initPage(row: any) {
  inspectCompany = row;
  findCompanyFeeitemList();
  findFeeItemList();
}

function keyupCompanyFeeEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findCompanyFeeitemList();
  }
}
function findCompanyFeeitemList() {
  ploading.value = true;
  companyFeeList.length = 0; //放入数据前清空数据
  const url = '/lab/inspectCompFeeitem/findInspectCompanyFeeitemList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchCompanyFeeForm.seachValue,
        companyCode: inspectCompany.companyCode
      }
    })
    .then((res: any) => {
      companyFeeList.push(...res.data);
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findFeeItemList();
  }
}

function findFeeItemList() {
  floading.value = true;
  feeItemList.length = 0; //放入数据前清空数据
  const url = '/lis/fee/item/findFeeItemList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        keyWords: searchForm.seachValue,
        companyCode: inspectCompany.companyCode
      }
    })
    .then((res: any) => {
      feeItemList.push(...res.data);

      floading.value = false;
    })
    .catch((err: any) => {
      floading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function feeItemRowClick({ row }: any) {
  if (isEmpty(inspectCompany)) {
    VxeMessage('请选择送检单位', VxeNotifyType.error);
    return;
  }
  const url = '/lab/inspectCompFeeitem/addCompanyFeeitem';
  let purposeItem = {
    companyId: inspectCompany.id,
    companyCode: inspectCompany.companyCode,
    feeId: row.id,
    feeCode: row.feeCode,
    price: row.price,
    origPrice: row.price,
    brokerage: 1,
    brokerageType: '1',
    brokerageCosts: 0,
    discount: 1,
    seq: row.seq
  };
  proxy.$http
    .post(url, purposeItem)
    .then((res: any) => {
      VxeMessage('成功', VxeNotifyType.success);
      findCompanyFeeitemList();
      findFeeItemList();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

async function saveCompanyFeeitemList() {
  let $Xtable = proxy.$refs.tatItemTableRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });

    const sveOrupdateSamples = [] as any[];
    updateRecords.forEach((e: any) => {
      const iISample: any = {
        id: e.id,
        companyId: e.companyId,
        companyCode: e.companyCode,
        feeId: e.feeId,
        feeCode: e.feeCode,
        price: e.price,
        discount: e.discount,
        brokerage: e.brokerage,
        brokerageType: e.brokerageType,
        brokerageCosts: e.brokerageCosts,
        origPrice: e.origPrice,
        seq: e.seq
      };

      sveOrupdateSamples.push(iISample);
    });

    if (sveOrupdateSamples.length > 0) {
      const url = '/lab/inspectCompFeeitem/saveOrUpdateCompFeeitem';
      const obj: any = {};
      obj.inspectCompanyFeeitemList = sveOrupdateSamples;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            findCompanyFeeitemList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}

function deleteBatchCompanyFee() {
  const sltTatItems = (proxy.$refs.tatItemTableRef as any).getCheckboxRecords();
  if (!(sltTatItems.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { inspectCompanyFeeitemList: sltTatItems };
        const url = '/lab/inspectCompFeeitem/batchDeleteCompanyFeeList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            if (res.status.code === 1) {
              findCompanyFeeitemList();
              findFeeItemList();
              VxeMessage('删除成功', VxeNotifyType.success);
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
function funDiscountPrice(row: any) {
  if (!IsEmpty(row.discount) && !IsEmpty(row.origPrice)) {
    row.price = parseFloat(String(row.discount * row.origPrice)).toFixed(2);
    //按照比例
    if (row.brokerageType == '1') {
      if (!IsEmpty(row.brokerage)) {
        row.brokerageCosts = parseFloat(String(row.price * row.brokerage)).toFixed(2);
      }
    }
  }
}
function funDiscountPrice1(row: any) {
  //按照比例
  if (row.brokerageType == '1') {
    if (!IsEmpty(row.brokerage)) {
      row.brokerageCosts = parseFloat(String(row.price * row.brokerage)).toFixed(2);
    }
  }
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>

<style lang="scss" scoped>
#labCompanyFeeitemDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }

  .rightTable {
    height: calc(100% - 40px);
  }
}
</style>